package com.sl.eurekaserver.command;

import org.springframework.web.client.RestTemplate;

import rx.Observable;
import rx.Subscriber;

import com.netflix.hystrix.HystrixObservableCommand;
import com.sl.eurekaserver.entity.User;

public class UserObservableCommand extends HystrixObservableCommand<User>{

	private RestTemplate restTemplate;
	
	private String userName;
	
	
	public UserObservableCommand(
			com.netflix.hystrix.HystrixObservableCommand.Setter setter,
			RestTemplate restTemplate,
			String userName) {
		super(setter);
		this.restTemplate = restTemplate;
		this.userName = userName;
	}

	@SuppressWarnings("deprecation")
	@Override
	protected Observable<User> construct() {
		
		//创建事件起源
		return Observable.create(new Observable.OnSubscribe<User>() {

			public void call(Subscriber<? super User> observer) {
				try{
					if(!observer.isUnsubscribed()){
						User user = restTemplate.getForObject("http://HELLO-SERVICE/hello/{userName}",
								User.class, userName);
						observer.onNext(user);
						observer.onCompleted();
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
		});
	}

}
